<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 启动会话并检查登录状态
session_start();
check_login();

// 权限验证（仅允许管理员操作）
if ($_SESSION['role'] != 1) {
    $_SESSION['error'] = '权限不足！';
    header("Location: coaches.php");
    exit();
}

// 验证参数
if (!isset($_GET['id']) || !isset($_GET['status'])) {
    $_SESSION['error'] = '请求参数不完整';
    header("Location: coaches.php");
    exit();
}

$coach_id = intval($_GET['id']);
$new_status = intval($_GET['status']);

// 参数有效性检查
if ($coach_id <= 0 || !in_array($new_status, [0, 1])) {
    $_SESSION['error'] = '无效的请求参数';
    header("Location: coaches.php");
    exit();
}

try {
    $db = db_connect();
    
    // 检查教练是否存在
    $stmt = $db->prepare("SELECT id FROM coaches WHERE id = ?");
    $stmt->execute([$coach_id]);
    if (!$stmt->fetch()) {
        $_SESSION['error'] = '教练不存在';
        header("Location: coaches.php");
        exit();
    }

    // 更新状态
    $update_stmt = $db->prepare("UPDATE coaches SET status = ? WHERE id = ?");
    $update_stmt->execute([$new_status, $coach_id]);

    // 操作结果反馈
    $status_text = $new_status ? '启用' : '禁用';
    $_SESSION['success'] = "教练状态已成功{$status_text}";

} catch(PDOException $e) {
    error_log('数据库错误: ' . $e->getMessage());
    $_SESSION['error'] = '系统繁忙，请稍后再试';
} catch(Exception $e) {
    $_SESSION['error'] = $e->getMessage();
}

// 返回教练列表
header("Location: coaches.php");
exit();